package main

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/leaf-rain-gitee/util/database/mysql"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
)

type User struct {
	ID             int            `json:"id" gorm:"primaryKey;column:id;type:int(11) auto_increment;comment:用户id"`                                             // 用户id
	Account        int            `json:"account" gorm:"column:account;type:int(11);not null;comment:账户"`                                                      // 账户
	Username       string         `json:"username" gorm:"column:username;type:varchar(50);not null;comment:用户名"`                                               // 用户名
	LoginPwd       sql.NullString `json:"login_pwd" gorm:"column:login_pwd;type:varchar(100);comment:登陆密码"`                                                    // 登陆密码
	PayPwd         sql.NullString `json:"pay_pwd" gorm:"column:pay_pwd;type:varchar(100);comment:支付密码"`                                                        // 支付密码
	Phone          sql.NullString `json:"phone" gorm:"column:phone;type:varchar(20);comment:手机号码"`                                                             // 手机号码
	Avatar         sql.NullString `json:"avatar" gorm:"column:avatar;type:varchar(100);comment:头像"`                                                            // 头像
	Signature      sql.NullString `json:"signature" gorm:"column:signature;type:varchar(150);comment:签名"`                                                      // 签名
	Wallet         string         `json:"wallet" gorm:"column:wallet;type:varchar(100);not null;index:gs_user_wallet_index;comment:钱包地址"`                      // 钱包地址
	Balance        sql.NullInt64  `json:"balance" gorm:"column:balance;type:bigint(20);default:0;comment:钱包余额"`                                                // 钱包余额
	Income         sql.NullInt64  `json:"income" gorm:"column:income;type:bigint(20);default:0;comment:今日收益"`                                                  // 今日收益
	InvitationCode int            `json:"invitation_code" gorm:"column:invitation_code;type:int(11);not null;index:gs_user_invitation_code_index;comment:邀请码"` // 邀请码
	Status         sql.NullInt32  `json:"status" gorm:"column:status;type:tinyint(1);default:1;comment:1 游客 2 正式用户"`                                           // 1 游客 2 正式用户
	UserType       sql.NullInt32  `json:"user_type" gorm:"column:user_type;type:tinyint(1);default:1;comment:1 普通账户 2 系统账户"`                                   // 1 普通账户 2 系统账户
	CreateTime     int64          `json:"create_time" gorm:"column:create_time;type:bigint(20);not null;comment:创建时间"`                                         // 创建时间
	UpdateTime     int64          `json:"update_time" gorm:"column:update_time;type:bigint(20);not null;comment:修改时间"`                                         // 修改时间
	Country        sql.NullString `json:"country" gorm:"column:country;type:varchar(20);comment:国家"`                                                           // 国家
	Language       sql.NullString `json:"language" gorm:"column:language;type:varchar(20);default:语言"`
}

// TableName returns the table name of the Item model
func (i *User) TableName() string {
	return "gs_user"
}

var (
	BlockchainQueryAddr = "10.255.22.102:1247"
	ErrBadRequest       = errors.New("区块链服务请求失败")
)

type balanceStr struct {
	BalancePre  string `json:"BalancePre"`
	BalanceTail string `json:"BalanceTail"`
}

func main() {
	db := mysql.NewMysql(&mysql.Config{
		Addr:        "rm-t4n32sq72629wa777.mysql.singapore.rds.aliyuncs.com:3306",
		User:        "admin_user",
		Password:    "UgFPxqVh345z211_C2",
		DbName:      "gluttonous",
		Prefix:      "gs_",
		Parameters:  "timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4",
		Debug:       true,
		Active:      10,
		Idle:        8,
		IdleTimeout: 4200,
	})

	rows, err := db.Table("gs_bill").Where("create_time between 1623254400000 and 1623686400000 and status =1").Select("consumer").Group("consumer").Rows()
	defer rows.Close()
	if err != nil {
		log.Fatal("获取钱包err", err)
	}
	var id int
	for rows.Next() {
		if err = rows.Scan(&id); err != nil {
			log.Println("scan user error", err)
			continue
		}
		if id == 0 {
			log.Println("获取id失败")
			continue
		}
		var user User
		if err = db.Model(&User{}).Select("wallet").Where("id = ?", id).First(&user).Error; err != nil {
			log.Println("获取用户信息失败")
			continue
		}
		balance, err := GetBlockChainGetAccountBalance(user.Wallet)
		if err != nil {
			fmt.Println(err)
			continue
		}
		if balance == 0 {
			continue
		}
		fmt.Println(user.Wallet, "---------->", balance)
		if err = db.Model(&User{}).Where("id = ?", id).Update("balance", balance).Error; err != nil {
			log.Println("修改金额失败", err)
			continue
		}
	}
	fmt.Println("success")
}

func getBlockChainGetAccountBalanceUrl(account string) string {
	return "http://" + BlockchainQueryAddr + "/getAccountBalance/" + account
}

// 查询钱包地址余额
func GetBlockChainGetAccountBalance(account string) (balance int64, err error) {
	resp, err := http.Get(getBlockChainGetAccountBalanceUrl(account))
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return 0, ErrBadRequest
	}
	body, err := ioutil.ReadAll(resp.Body)
	var a = balanceStr{}
	err = json.Unmarshal(body, &a)
	if err != nil {
		return 0, err
	}
	//fmt.Println(a.BalancePre)
	//fmt.Println(a.BalanceTail)
	balance, err = strconv.ParseInt(a.BalancePre+a.BalanceTail[:6], 10, 64)
	if err != nil {
		fmt.Println("金额序列化错误")
	}
	return balance, err
}
